package com.bangyo.usertype;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.hibernate.HibernateException;
import org.sothis.util.JsonUtils;

/**
 * Blog使用的ElementAttributes。 2007-10-10 下午02:38:38
 */
public class ElementAttributesUserType extends AbstractMutableUserType
{
    private static final int[] SQL_TYPES =
    {
        Types.VARCHAR
    };

    @SuppressWarnings("unchecked")
    public Object deepCopy(Object value) throws HibernateException
    {
        if (value==null)
            return null;

        Map<String, Boolean> newValue = new HashMap<String, Boolean>();
        newValue.putAll((Map<String, Boolean>)value);

        return newValue;
    }

    public boolean isMutable()
    {
        return true;
    }

    public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
        throws HibernateException, SQLException
    {
        if (rs.wasNull())
            return null;

        String elementAttributes = rs.getString(names[0]);
        if (null==elementAttributes)
            return null;

        Map<String, Boolean> _elementAttributes = new HashMap<String, Boolean>();
        JsonUtils.toBean(_elementAttributes, JSONObject
            .fromObject(elementAttributes));
        return _elementAttributes;
    }

    @SuppressWarnings("unchecked")
    public void nullSafeSet(PreparedStatement st, Object value, int index)
        throws HibernateException, SQLException
    {
        if (value==null)
        {
            st.setNull(index, Types.VARCHAR);
        }
        else
        {
            Map<String, Boolean> elementAttributes = (Map<String, Boolean>)value;
            Object jsonObject = JsonUtils.fromBean(elementAttributes);
            st.setString(index, jsonObject.toString());
        }
    }

    public Class<?> returnedClass()
    {
        return Map.class;
    }

    public int[] sqlTypes()
    {
        return SQL_TYPES;
    }

}
